﻿$(function () {
    $('#tablist').tabs({
        onBeforeClose: function (title, index) {
            var entity = ko.contextFor($('#tablist').tabs('getTab', index)[0]).$data;
            if (entity.state() == 'Modified') {
                var r = confirm("You has modified content.Do you want to save before close?");
                if (r == true) {
                    manager.saveChanges([entity]).then(function (data) {
                        alert('Save ' + entity.Title() + ' successful.');
                        updateTabstate('');
                    }).fail(function (e) {
                        alert(e);
                    });
                }
                else {
                    ////Remove entity CategoryQuestion that un-used: cascahe delete
                    var length = entity.CategoryQuestions().length;
                    for (var i = 0; i < length; i++) {
                        entity.CategoryQuestions()[0].entityAspect.setDetached();
                    }
                    entity.entityAspect.setDetached();
                    entity.state('Unchanged');
                }
            }
            
            

        },
        onClose: function (title, index) {          
            for (var i = 0; i < viewModel.questionsdetail().length; i++){
                if (title == viewModel.questionsdetail()[i].text) {
                    viewModel.questionsdetail.splice(i, 1);
                }
            }
        }
    });
    $('#qq').tree({
        onDblClick: function (node) {           
            manager.fetchEntityByKey("CompetencyQuestion", node.id).then(function (result) {
                var entity = result.entity;
                if (!checkExisttab(entity)) {
                entity.state = ko.observable('Unchanged');
                entity.categories = viewModel.categories;
                entity.selectedcategory = ko.observableArray();

                //Category binding
                for (var i = 0; i < entity.CategoryQuestions().length; i++) {
                    entity.selectedcategory.push(entity.CategoryQuestions()[i].CategoryId());
                }
                //Answer binding                
                for (var i = 0; i < entity.QuestionAnswers().length; i++) {
                    entity.QuestionAnswers()[i].Title = entity.QuestionAnswers()[i].Answer().Title();
                }
                //Observe changes
                entityFunction4Q(entity, node);
                             
                viewModel.questionsdetail.push(entity);
                var newtab = $('#tabs').clone();              
                $('#tablist').tabs('add', {
                    title: entity.Title(),
                    content: newtab.html(),
                    closable: true,
                    tools: [{
                        iconCls: 'icon-save',
                        handler: function () {
                            if (manager.hasChanges()) {
                                manager.saveChanges([entity]).then(function (data) {
                                    alert('Save ' + entity.Title() + ' successful.');
                                    entity.state('Unchanged');
                                }).fail(function (e) {
                                    alert(e);
                                });
                            } else {
                                alert('Nothing to save');
                            }
                        }
                    }]
                });

                var obj = $('#tablist').tabs('getTab', $('#tablist').tabs('tabs').length - 1);
                ko.applyBindings(entity, obj[0]);
                }
            }).fail(function (e) {
                alert(e);
            });

        }
    });

    

});

function checkExisttab(entity) {
    for (var i = 0 ; i < $('#tablist').tabs('tabs').length; i++) {
        var name = $('#tablist').tabs('getTab', i).panel('options').title;
        if (name == entity.Title()) {
            return true;
        }
    }
    return false;
}
function entityFunction4Q(entity, node) {
    entity.removeAnswer = function () {
        var rowindex = $('#tablist').tabs('getSelected').find('#cc')[0].selectedIndex;
        var tabindex = $('#tablist').tabs('getTabIndex', $('#tablist').tabs('getSelected'));
        viewModel.questionsdetail()[tabindex].QuestionAnswers()[rowindex].entityAspect.setDeleted();
        updateTabstate('(Modified1)');
    }
    entity.QuestionAnswers.subscribe(function (changes) {
        changes.forEach(function (change) {
            if (change.status === 'added') {
                change.value.Title = change.value.Answer().Title();
            }
            updateTabstate('(Modified2)');
        });
    }, null, "arrayChange");
    entity.selectedcategory.subscribe(function (changes) {
        changes.forEach(function (change) {
            if (change.status === 'added') {
                var ent = createCategoryQuestions(node.id, change.value, entity);
            }
            if (change.status === 'deleted') {
                removeCategoryQ(node.id, change.value, entity);
            }
            updateTabstate('(Modified3)');
        });
    }, null, "arrayChange");
    entity.entityAspect.propertyChanged.subscribe(function (changes) {
        //updateTabstate(entity, '(Modified4)');
        entity.state('Modified');
    }, null, "arrayChange");
}
function createQuestionAnswers(QuestionId, AnswerId, Title) {
    var QuestionAnswers = manager.createEntity('QuestionAnswer', { QuestionId: QuestionId, AnswerId: AnswerId, Title: Title});
    return QuestionAnswers;
}
function createCategoryQuestions(AquestionId, CategoryId, entity) {
    var deletedCat = manager.getEntities('CategoryQuestion', breeze.EntityState.Deleted);
    var tmp = manager.getEntities('CategoryQuestion', breeze.EntityState.Added);
    var check = true;
    for (var i = 0; i < deletedCat.length; i++) {
        if (CategoryId == deletedCat[i].CategoryId()) {
            deletedCat[i].entityAspect.rejectChanges();
            entity.CategoryQuestions().push(deletedCat[0]);
            check = false;
        }       
    }
    if (check) {
        var CategoryQuestion = manager.createEntity('CategoryQuestion', { AquestionId: AquestionId, CategoryId: CategoryId });
    }
}
function removeCategoryQ(QuestionId, CategoryId, entity) {
    for (var i = 0; i < entity.CategoryQuestions().length; i++) {
        var item = entity.CategoryQuestions()[i];
        if (item.CategoryId() == CategoryId && item.AquestionId() == QuestionId) {
            if (item.entityAspect.entityState.name == 'Added') {
                item.entityAspect.setDetached();
            } else {
                item.entityAspect.setDeleted();
            }
        }
    }
}
function updateTabstate(entity, state) {
    entity.state(state);
    //var tab = $('#tablist').tabs('getSelected');  // get selected panel
    //var name = tab.panel('options').title;
    ////var model = ko.contextFor(tab[0]).$data;
    //$('#tablist').tabs('update', {
    //    tab: tab,
    //    options: {
    //        title: name + ' ' + state
    //    }
    //});
    //ko.cleanNode(tab[0]);
    //ko.applyBindings(model, tab[0]);
}


viewModel.addQuestion = function () {   
    var newtab = $('#tabs').clone();   
    var en = {
        Title: ko.observable(''),
        state: ko.observable('Added'),
        Text: ko.observable(''),
        Feedback: ko.observable(''),
        categories: viewModel.categories,
        selectedcategory: ko.observableArray(),
        QuestionAnswers: ko.observableArray(),
        removeAnswer : function () {
            var rowindex = $('#tablist').tabs('getSelected').find('#cc')[0].selectedIndex;
            en.QuestionAnswers.splice(rowindex, 1);
        }
    }

    $('#tablist').tabs('add', {
        title: 'New question', //Do not edit this title
        content: newtab.html(),
        closable: true,
        tools: [{
            iconCls: 'icon-save',
            handler: function () {
                var needadd = []; //Array of entity
                var newQuestion = manager.createEntity('CompetencyQuestion', { Title: en.Title(), Text: en.Text(), Feedback: en.Feedback() });
                //Add list of categories
                for (var i = 0; i < en.selectedcategory().length; i++) {
                    var QA = manager.createEntity('CategoryQuestion', { AquestionId: newQuestion.Id(), CategoryId: en.selectedcategory()[i] });
                    newQuestion.CategoryQuestions.push(QA);
                    needadd.push(QA);
                }
                //Add list of answers
                for (var i = 0; i < en.QuestionAnswers().length; i++) {
                    var QA = manager.createEntity('QuestionAnswer', { QuestionId: newQuestion.Id(), AnswerId: en.QuestionAnswers()[i].AnswerId });
                    newQuestion.QuestionAnswers.push(QA);
                    needadd.push(QA);
                }
                manager.addEntity(newQuestion);
                needadd.unshift(newQuestion);
                manager.saveChanges(needadd).then(function (data) {
                    alert('Save ' + en.Title() + ' successful.');
                    en.state('Unchanged');
                });
            }
        }]
    });   
    var obj = $('#tablist').tabs('getTab', $('#tablist').tabs('tabs').length - 1);
    ko.applyBindings(en, obj[0]);
}

viewModel.copyQuestion = function () {
    var node = $('#qq').tree('getSelected');
    var index = $('#tablist2').tabs('getTabIndex', $('#tablist2').tabs('getSelected'));
    var model = ko.contextFor($('#tablist2').tabs('getTab', index)[0]).$data;
    if(node != null){
        var check = true; var valid = true;
        for (var i = 0; i < model.QuestionAnswers().length; i++) {
            if (model.QuestionAnswers()[i].QuestionId() == node.id) {
                check = false; break;
            }
        }
        if (check) {
            var deletedCat = manager.getEntities('QuestionAnswer', breeze.EntityState.Deleted);
            for (var i = 0; i < deletedCat.length; i++) {
                if (node.id == deletedCat[i].QuestionId()) {
                    deletedCat[i].entityAspect.rejectChanges();
                    model.QuestionAnswers().push(deletedCat[0]);
                    valid = false;
                }
            }
        }
        if (check && valid) {           
            if ($('#tablist2').tabs('getTab', i).panel('options').title != 'New answer') {
                var newobj = createQuestionAnswers(node.id, model.Id(), node.text);
            } else {
                var obj = new Object();
                obj.Title = node.text;
                obj.QuestionId = node.id;
                model.QuestionAnswers.push(obj);
            }
        }
    }
    

}
